insert into  asm_gecera_anag_utenti_v2

    select distinct a.NUMEROINDIVIDUALE, so.sog_ragsoc,
    case when so.SOG_COGN is null then a.cognome else sog_cogn end sog_cogn,
    case when so.SOG_nome is null then a.nome else sog_nome end sog_nome,
    
    so.sog_codfis,
    so.sog_pariva,
    so.eletopo_des,
    so.IND_NUM,
    so.IND_SUF,
    so.sog_id,
    a.NUMERO_FAMI,'DOM',
    a.DATA_NASCITA,
     case when to_number(substr(a.codice_fiscale,10,2)) <=31 then 'M' else 'F' end sesso,
     su.comp,
    1
    from asm_anagrafe_terni a,
    (select s.* from v_soggetto s ,(select sog_codfis,max(sog_id) sog_id from v_soggetto  where az_id ='01'group by sog_codfis) s1
    where s.sog_id = s1.sog_id
    and s.az_id='01'
    --and s.sog_codfis in ('PTRNNA41A65L117S')
    ) so,
   v_conubifrn ub,
    (select numero_fami,sum(1) comp from asm_anagrafe_terni a where a.CODICE_TIPO_EVENTO is null or a.CODICE_TIPO_EVENTO in ('I')
    group by numero_fami) su
    where a.codice_fiscale(+)= so.SOG_CODFIS
  AND ub.sog_idclifin = so.sog_id
             AND ub.az_id = '01'
            AND ub.ver_dtfine = TO_DATE ('31129999', 'ddmmyyyy')
           AND ub.sta_idsys = 2
            and ub.tcon_id='10'
                
    and a.NUMERO_FAMI=su.numero_fami(+)

  
  
  --select * from v_soggetto where sog_codfis='PTRNNA41A65L117S';
    --and a.numero_fami = 51286